package per.mnxc.common;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @BelongsProject: spring_stu
 * @BelongsPackage: per.mnxc.common
 * @Author: mnxc
 * @CreateTime: 2022-11-15  13:48
 * @Description: 文件下载和上传
 * @Version: 1.0
 */
@RestController
@Api(tags = "文件下载和上传")
@RequestMapping("/common")
@CrossOrigin(origins = "*",maxAge = 3600)
public class CommonController {


    String basePath = StaticPathUtil.PlantImgPath;
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //1.获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //2.获取文件名后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //3.uuid生成文件名，并拼接
        String fileName = UUID.randomUUID().toString()+suffix;
        //4.判断basePath所在目录是否存在,无则创建目录
        File dir = new File(basePath);
        if(!dir.exists()){
            //4-1.目录不存在，则创建目录
            dir.mkdirs();
        }
        //5.保存文件
        try{
            file.transferTo(new File(basePath+"/"+fileName));
            return R.success(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error("保存图片失败");
    }
    @ApiOperation("文件下载")
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //文件输入流
            FileInputStream inputStream = new FileInputStream(basePath+"/"+name);

            //文件输出流
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            int len =0;
            byte [] bytes = new byte[1024];
            while ((len = inputStream.read(bytes))!=-1){
                outputStream.write(bytes);
                outputStream.flush();
            }
        }catch (IOException e) {
            e.printStackTrace();
        }

    }
}
